<script setup lang="tsx">
import { reactive, ref, unref } from 'vue'
import { getDictPageListApi, batchDelDict } from '@/api/dict'
import { useTable } from '@/hooks/web/useTable'
import { useI18n } from '@/hooks/web/useI18n'
import { Table, TableColumn } from '@/components/Table'
import { Search } from '@/components/Search'
import { FormSchema } from '@/components/Form'
import { ContentWrap } from '@/components/ContentWrap'
import Write from './components/Write.vue'
import { Dialog } from '@/components/Dialog'
import { BaseButton } from '@/components/Button'
import { useSearch } from '@/hooks/web/useSearch'
import { ElDrawer } from 'element-plus'
import DictItem from './components/DictItem.vue'

const { t } = useI18n()

const { searchRegister, searchMethods } = useSearch()
const { getFormData } = searchMethods
const ids = ref<string[]>([])

const { tableRegister, tableState, tableMethods } = useTable({
  fetchDataApi: async () => {
    const formData = await getFormData()
    const res = await getDictPageListApi({
      dictName: formData.dictName,
      dictCode: formData.dictCode,
      page: { size: unref(pageSize), current: unref(currentPage) }
    })
    return {
      list: res.result.records || [],
      total: res.result.total
    }
  },
  fetchDelApi: async () => {
    const res = await batchDelDict(unref(ids))
    return !!res
  }
})
const { dataList, loading, total, currentPage, pageSize } = tableState

const { getList, refresh, delList, getElTableExpose } = tableMethods

const tableColumns = reactive<TableColumn[]>([
  {
    field: 'index',
    label: t('userDemo.index'),
    type: 'index'
  },
  {
    field: 'dictName',
    label: t('dict.dictName')
  },
  {
    field: 'dictCode',
    label: t('dict.dictCode')
  },
  {
    field: 'createTime',
    label: t('tableDemo.displayTime')
  },
  {
    field: 'description',
    label: t('userDemo.remark')
  },
  {
    field: 'action',
    label: t('userDemo.action'),
    width: 250,
    slots: {
      default: (data: any) => {
        const row = data.row
        return (
          <>
            <BaseButton type="primary" onClick={() => action(row, 'edit')}>
              {t('exampleDemo.edit')}
            </BaseButton>
            <BaseButton type="success" onClick={() => dictItemAction(row)}>
              {t('dict.dictItem')}
            </BaseButton>
            <BaseButton type="danger" onClick={() => delData(row)}>
              {t('exampleDemo.del')}
            </BaseButton>
          </>
        )
      }
    }
  }
])

const delLoading = ref(false)
const delData = async (row) => {
  const elTableExpose = await getElTableExpose()
  ids.value = row ? [row.id] : elTableExpose?.getSelectionRows().map((v) => v.id) || []
  delLoading.value = true

  await delList(unref(ids).length).finally(() => {
    delLoading.value = false
  })
}

const searchSchema = reactive<FormSchema[]>([
  {
    field: 'dictName',
    label: t('dict.dictName'),
    component: 'Input'
  },
  {
    field: 'dictCode',
    label: t('dict.dictCode'),
    component: 'Input'
  }
])

const searchParams = ref({})
const setSearchParams = (data: any) => {
  searchParams.value = data
  getList()
}

const dialogVisible = ref(false)
const dictItemVisible = ref(false)
const dialogTitle = ref('')

const currentRow = ref()
const actionType = ref('')

const writeRef = ref<ComponentRef<typeof Write>>()

const saveLoading = ref(false)

const action = (row: any, type: string) => {
  dialogTitle.value = t(type === 'edit' ? 'exampleDemo.edit' : 'exampleDemo.detail')
  actionType.value = type
  currentRow.value = row
  dialogVisible.value = true
}
const dictItemAction = (row) => {
  currentRow.value = row
  dictItemVisible.value = true
}
const AddAction = () => {
  dialogTitle.value = t('exampleDemo.add')
  currentRow.value = undefined
  dialogVisible.value = true
  actionType.value = ''
}

const save = async () => {
  const write = unref(writeRef)
  const formData = actionType.value === 'edit' ? await write?.updateData() : await write?.submit()
  if (formData) {
    saveLoading.value = true
    setTimeout(() => {
      saveLoading.value = false
      dialogVisible.value = false
      refresh()
    }, 1000)
  }
}
</script>

<template>
  <ContentWrap>
    <Search
      :schema="searchSchema"
      @reset="setSearchParams"
      @search="setSearchParams"
      @register="searchRegister"
    />
    <div class="mb-10px">
      <BaseButton type="primary" @click="AddAction">{{ t('exampleDemo.add') }}</BaseButton>
    </div>
    <Table
      v-model:pageSize="pageSize"
      v-model:currentPage="currentPage"
      @refresh="refresh"
      :columns="tableColumns"
      default-expand-all
      node-key="id"
      :data="dataList"
      :loading="loading"
      :pagination="{
        total
      }"
      @register="tableRegister"
    />
  </ContentWrap>
  <ElDrawer v-model="dictItemVisible" :title="t('dict.dictItem')" size="40%">
    <DictItem :current-row="currentRow" />
  </ElDrawer>
  <Dialog v-model="dialogVisible" :title="dialogTitle" maxHeight="150px" width="30%">
    <Write v-if="actionType !== 'detail'" ref="writeRef" :current-row="currentRow" />
    <template #footer>
      <BaseButton
        v-if="actionType !== 'detail'"
        type="primary"
        :loading="saveLoading"
        @click="save"
      >
        {{ t('exampleDemo.save') }}
      </BaseButton>
      <BaseButton @click="dialogVisible = false">{{ t('dialogDemo.close') }}</BaseButton>
    </template>
  </Dialog>
</template>
